package cn.lg.soar.core.handler.ex;

import java.util.Objects;
import java.util.function.Function;

/**
 * @author luguoxiang
 * @date 2022/4/4
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class ExHandler<T extends Throwable> {

    public final Class<T> type;
    public final Function<Throwable, ErrorResult> handler;

    public ExHandler(Class<T> type, Function<Throwable, ErrorResult> handler) {
        this.type = type;
        this.handler = handler;
    }

    /**
     * 是否支持该处理异常
     * @param e
     * @return
     */
    public boolean support(Class<? extends Throwable> e) {
        return type.isAssignableFrom(e);
    }

    /**
     * 处理异常
     * @param ex
     * @return
     */
    public ErrorResult handle(Throwable ex) {
        return handler.apply(ex);
    }

    @Override
    public boolean equals(Object object) {
        if (this == object) {
            return true;
        }
        if (object == null || getClass() != object.getClass()) {
            return false;
        }
        ExHandler<?> exHandler = (ExHandler<?>) object;
        return Objects.equals(type, exHandler.type);
    }

    @Override
    public int hashCode() {
        return Objects.hash(type);
    }
}
